package com.geeksaga.service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import com.geeksaga.advice.LoggingAspect;
import com.geeksaga.message.GeekSagaMessage;

/**
 * @author newbie
 * @since 0.1
 */
@Component
public class SendMailService {
    
    protected final Log logger = LogFactory.getLog(SendMailService.class);
    
    @Autowired JavaMailSender mailSender;

//    public SendMailService(JavaMailSender mailSender) {
//        this.mailSender = mailSender;
//    }
    
    public void sendMail(GeekSagaMessage message) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        
        if(message.getReceivers().length == 0)
            return;
        
        if(message.getReceivers().length > 100) {
            for(String to : message.getReceivers()){
                sendMail(to, message, mimeMessage);
            }
        } else
            sendMail(message, mimeMessage);
    }

    private void sendMail(GeekSagaMessage message, MimeMessage mimeMessage2) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "UTF-8");
        
        try {
            logger.info(message.getReceivers()[0]);
            helper.setTo(message.getReceivers());
            helper.setFrom(message.getFrom());
            helper.setSubject(message.getTitle());
            helper.setText(message.getMessage(), message.isHTML());
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        
        mailSender.send(mimeMessage);
    }
    
    private void sendMail(String to, GeekSagaMessage message, MimeMessage mimeMessage) {
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, "UTF-8");
        
        try {
            helper.setTo(to);
            helper.setFrom(message.getFrom());
            helper.setSubject(message.getTitle());
            helper.setText(message.getMessage(), message.isHTML());
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        
        mailSender.send(mimeMessage);
    }
}